var Bulletins = mongoose.model('community_bulletins');
var Community = mongoose.model('community');
var Supplement = mongoose.model('community_supplements');
var Users = mongoose.model('user');
var async = require('async');
var toolUtil = require('../common/utils/toolUtil');
var geolib = require('geolib');
var cacheUtil = require('../common/utils/cacheUtil');
var moment = require('moment');
var communitySupplement = mongoose.model('community_supplements');
var UserFollowups = mongoose.model('user_followups');
var freshNews = mongoose.model('system_freshNews');
var communityApplication = mongoose.model('community_applications');
var systemService = require('./systemService');
var card = mongoose.model('community_card');
var communityCard = mongoose.model('card');
var weekReport = mongoose.model('weekly_report');
var weekScore = mongoose.model('user_week_score');
var Question = mongoose.model('question');
var questionService = require('./questionService');

/**
 * 根据小区ObjID查询所有公告
 */
exports.getCommunityBulletinService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;
            Bulletins.find({
                'community': user.community._id,
                isValid: true
            }, '_id title imageURL dateCreated').sort('-dateCreated').skip(index).limit(listPageSize).exec(callback);
        }
    });
};

exports.getDetailCommunityBulletinService = function (bulletinId, callback) {
    Bulletins.findOne({_id: bulletinId}, '_id title imageURL desc dateCreated', function (err, result) {
        if (result != null) {
            var date = moment(result.dateCreated).format('YYYY-MM-DD HH:mm');
            var header = '<B><font  size="5">' + result.title + '</font></B><br>' + date + '<br><br>'
            result.desc = header + result.desc;
        }
        callback(err, result);
    });
};

exports.postCommunityApplicationService = function (input, callback) {
    var temp = new communityApplication(input);
    temp.save(callback);
};


/**
 * 发布公告
 */
exports.postCommunityBulletinService = function (token, input, callback) {

    if (input.id == null) {
        var temp = new Bulletins();
        temp.title = input.title;
        temp.desc = input.desc;
        temp.imageURL = input.imageURL;
        temp.community = input.community;
        temp.save(function (err, notice) {
            callback(err, null);
            systemService.generateTopicHtml(temp, noticePath);
        });
    } else {
        Bulletins.update({_id: input.id}, {
            title: input.title,
            desc: input.desc,
            imageURL: input.imageURL,
            community: input.community
        }, callback);
        systemService.generateTopicHtml(input, noticePath);
    }
};

//获取小区详细信息
exports.getCommunityByCommunityIdService = function (token, communityId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            Community.findById(communityId, '_id communityName households country province city county populationSize communityAddress communityLogo communityPostCode location phoneList')
                .populate('country', '_id name').populate('province', '_id name').populate('county', '_id name')
                .exec(function (err, result) {
                    if (err) {
                        callback(err, null);
                    } else {
                        if (result == null) {
                            var msg = {
                                "message": 'No such community'
                            };
                            callback(msg, null);
                        } else {
                            var key = 'app:community:peopleNum';
                            redisClient.HGET(key, communityId, function (err, value) {
                                Users.count({community: communityId, userType: 'talent'}, function (err, count) {
                                    result._doc['numberOfTalent'] = count;
                                    if (user.mobilePhone != null && user.mobilePhone.indexOf('700700') == 0) {
                                        result._doc['switchFlag'] = true;
                                    } else {
                                        result._doc['switchFlag'] = false;
                                    }

                                    if (value != null) {
                                        result._doc['numberOfUser'] = JSON.parse(value).num;
                                        callback(err, result)
                                    } else {
                                        Users.count({community: communityId}, function (err, count) {
                                            result._doc['numberOfUser'] = count;
                                            callback(err, result)
                                            redisClient.HSET(key, communityId, JSON.stringify({
                                                id: result._id,
                                                name: result.communityName,
                                                num: count
                                            }))
                                        })
                                    }
                                })
                            });
                        }
                    }
                });
        }
    });
};

exports.getUserCommunityDetailService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            Community.findOne({_id: user.community._id}, 'communityName communityAddress phoneList communityLogo')
                .populate('phoneList.user', 'nickName images')
                .exec(function (err, result) {
                    result.phoneList.forEach(function (temp) {
                        if (temp.user == null) {
                            temp.user = undefined;
                        }
                    })

                    if (user.mobilePhone != null && user.mobilePhone.indexOf('700700') == 0) {
                        result._doc['switchFlag'] = true;
                    } else {
                        result._doc['switchFlag'] = false;
                    }

                    callback(err, result);
                });
        }
    })
};


exports.backOfficeGetCommunityDetailService = function (communityId, callback) {
    Community.findOne({_id: communityId}, callback);
};

//根据小区名字进行模糊查询
exports.searchByCityAndNameService = function (cityId, communityName, callback) {
    Community.find({
        'city': cityId,
        'communityName': new RegExp(communityName)
    }, '_id communityName country province city county populationSize communityAddress communityPostCode x_position y_position')
        .populate('country', '_id name').populate('province', '_id name').populate('city', '_id name').populate('county', '_id name').exec(callback);
};


/*  宝宝树66小区二次改造    add   guo.xiaomin  20170815   start   */
// 管理多个小区server兼容性走查，多余逗号删除
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170807   start   */
// 根据小区ID取得城市ID
exports.searchCityIdByCommunityIdService = function (communityId, callback) {
    Community.findOne({'_id': communityId}, {"_id":0, "cityId":1} ,callback);
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170807   end   */
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170815   end   */

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170815   start   */
exports.searchCommunityInfoByCommunityIdService = function (communityId, callback) {
    Community.findOne({'_id': communityId} ,callback);
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170815   end   */

// //======================Communities related=================================


exports.getCommunityListByCoordinates = function (latitude, longitude, callback) {

    //restClient.get('http://api.map.baidu.com/place/v2/search?&query=小区&region=上海&scope=2&output=json&ak=AvRqTglpaKICTZ5iwyn06KZj&radius=1000&page_size=20&page_num=0&location='
    //+ latitude + ',' + longitude, function (data, response) {
    //    if (response.statusCode == 200) {
    //
    //        Community.findOne({'communityName': '宝宝树66小区'}, function (err, result) {
    //            var temp = {
    //                "name": result.communityName,
    //                "location": {
    //                    "lat": result.location.latitude,
    //                    "lng": result.location.longitude
    //                },
    //                "address": result.communityAddress,
    //                "detail_info": {
    //                    "distance": 0
    //                }
    //            };
    //            var communities = JSON.parse(data);
    //            communities.results.unshift(temp);
    //            callback(null, communities);
    //        });
    //
    //
    //    } else {
    //        var err = {
    //            "message": 'statusCode:' + response.statusCode
    //        };
    //        callback(err, null);
    //    }
    //
    //}).on('error', function (err) {
    //    logger.error('get Community List by Coordinates went wrong on the request' + err.message);
    //});

    Community.find({isValid: true}, '').limit(20).exec(function (err, results) {
        var communities = {
            "results": []
        };
        results.forEach(function (result) {

            var dis = '';

            if (latitude == 0 || longitude == 0) {
                dis = ''
            } else {
                var distance = geolib.getDistance(
                    {latitude: latitude, longitude: longitude},
                    {latitude: result.location.latitude, longitude: result.location.longitude}
                );
                if (distance > 1000) {
                    var aa = distance / 1000;
                    dis = aa.toFixed(1) + 'km';
                } else {
                    dis = distance + 'm';
                }
            }

            var temp = {
                "_id": result._id,
                "name": result.city + '  ' + result.communityName,
                "location": {
                    "lat": result.location.latitude,
                    "lng": result.location.longitude
                },
                "address": result.communityAddress,
                "detail_info": {
                    "distance": dis
                },
                "order": distance
            };
            communities.results.unshift(temp);
        });

        communities.results.sort(function (a, b) {
            return a.order - b.order;
        });
        communities.results.forEach(function (t) {
            t.order = undefined;
        });

        callback(null, communities);
    });

};

/**
 * 获取小区达人排行榜
 * @param token
 * @param callback
 */
exports.getCommunityTalentService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Users.find({
                'userType': 'talent',
                'community': user.community._id
            }, '_id nickName images userPortrait speciality gender authenticationStatus').populate('userPortrait', '_id value')
                .exec(function (err, results) {
                    if (results != null) {
                        async.each(results, function (talent, callbackInner) {
                            UserFollowups.findOne({
                                'user': user._id,
                                'followUser': talent._id
                            }, '', function (err, result) {
                                if (result == null) {
                                    talent._doc['isFollowup'] = 'No'
                                } else {
                                    talent._doc['isFollowup'] = 'Yes'
                                }
                                callbackInner();
                            })
                        }, function (err) {
                            callback(err, results);
                        })

                    }
                })
        }
    });
}

exports.getCommunityTalentNewService = function (page, token, callback) {

    var index = Number(page) * listPageSize;

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Users.find({
                'userType': 'talent',
                'community': user.community._id
            }, '_id nickName images userPortrait speciality gender authenticationStatus userRole').populate('userPortrait', '_id value').skip(index).limit(listPageSize)
                .exec(function (err, results) {
                    if (results != null) {
                        async.each(results, function (talent, callbackInner) {
                            UserFollowups.findOne({
                                'user': user._id,
                                'followUser': talent._id
                            }, '', function (err, result) {
                                if (result == null) {
                                    talent._doc['isFollowup'] = 'No'
                                } else {
                                    talent._doc['isFollowup'] = 'Yes'
                                }
                                callbackInner();
                            })
                        }, function (err) {
                            callback(err, results);
                        })
                    }
                })
        }
    });
}


/**
 * 根据关键字查询
 * @param keyword
 * @param callback
 */
exports.getCommunityListByKeywordService = function (keyword, latitude, longitude, callback) {

    Community.find({'communityName': new RegExp(keyword), isValid: true}, '', function (err, results) {
        var communities = {
            "results": []
        };
        results.forEach(function (result) {

            var dis = '';

            if (latitude == 0 || longitude == 0) {
                dis = ''
            } else {
                var distance = geolib.getDistance(
                    {latitude: latitude, longitude: longitude},
                    {latitude: result.location.latitude, longitude: result.location.longitude}
                );
                if (distance > 1000) {
                    var aa = distance / 1000;
                    dis = aa.toFixed(1) + 'km';
                } else {
                    dis = distance + 'm';
                }
            }

            var temp = {
                "_id": result._id,
                "name": result.city + '  ' + result.communityName,
                "location": {
                    "lat": result.location.latitude,
                    "lng": result.location.longitude
                },
                "address": result.communityAddress,
                "detail_info": {
                    "distance": dis
                },
                "order": distance
            };
            communities.results.unshift(temp);
        });

        communities.results.sort(function (a, b) {
            return a.order - b.order;
        });
        communities.results.forEach(function (t) {
            t.order = undefined;
        });

        callback(null, communities);
    });

    //restClient.get('http://api.map.baidu.com/place/v2/search?&query=小区、' + keyword + '&region=上海&scope=2&output=json&ak=AvRqTglpaKICTZ5iwyn06KZj&radius=1000&page_size=20&page_num=0&location='
    //+ latitude + ',' + longitude, function (data, response) {
    //    if (response.statusCode == 200) {
    //        callback(null, JSON.parse(data));
    //    } else {
    //        var err = {
    //            "message": 'statusCode:' + response.statusCode
    //        };
    //        callback(err, null);
    //    }
    //}).on('error', function (err) {
    //    logger.error('get Community List by keyword went wrong on the request' + err.message);
    //});
};

/**
 * 获取商户列表
 */
exports.getCommunityAroundListService = function (page, status, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;
            if (status == '全部') {
                CommunityAround.find({'community': user.community._id}, 'category status name images address title desc telephone businessHours averageConsumption').skip(index).limit(listPageSize).populate('category', '_id value').exec(callback);
            } else {
                CommunityAround.find({
                    'status': status,
                    'community': user.community._id
                }, 'category status name images address title desc telephone businessHours averageConsumption').skip(index).limit(listPageSize).populate('category', '_id value').exec(callback);
            }
        }
    })
};

/**
 * 获取商户详情
 */
exports.getCommunityAroundDetailsService = function (id, callback) {
    CommunityAround.findOne({_id: id}, 'category status name images address title album desc telephone businessHours averageConsumption comments.desc comments.createdBy comments.dateCreated dateCreated createdBy').populate('category', '_id value')
        .populate('comments.createdBy', '_id nickName images').populate('createdBy', '_id nickName').exec(function (err, results) {
            if (results != null && results.comments != null) {
                results.comments.sort(function (c1, c2) {
                    return c2.dateCreated - c1.dateCreated;
                });
            }
            callback(null, results);
        });
};

/**
 * 小区周边评论
 */
exports.postCommentService = function (aroundId, token, input, callback) {
    async.waterfall([
        function (callbackInner) {
            CommunityAround.findOne({'_id': aroundId}, function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == undefined) {
                var err = {
                    "message": 'CommunityAround not found'
                };
                callback(err, null);
            } else {

                toolUtil.getUserByToken(token, function (err, user) {
                    if (err) {
                        callback(err, null);
                    } else {
                        var commend = {
                            'desc': input.desc,
                            'createdBy': user._id
                        };
                        CommunityAround.update({_id: aroundId}, {$push: {'comments': commend}}).exec(callback);
                    }
                });
            }
        }
    ])
}

/**
 * 查询全部小区
 */
exports.getAllCommunityService = function (callback) {

    Community.find(null).exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such community'
            }
            callback(msg, null);
        }
    });
};

exports.postCommunitySupplementService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var temp = new communitySupplement();
            temp.createdBy = user._id;
            temp.id = input.id;
            temp.desc = input.desc;
            temp.phone = input.phone;
            temp.address = input.address;
            temp.community = user.community._id;
            temp.save(callback);

            var message = '感谢您的理解和支持，如有其它问题，欢迎随时撩我哦~如果你对我印象还不错，欢迎推荐给身边的亲朋好友哈~';
            toolUtil.pushCustomerServiceMessage(user, message);
        }
    });
};

exports.getCommunitySupplementListService = function (communityId, callback) {
    if (communityId == '1') {
        communitySupplement.find({}, 'dateCreated createdBy desc community status').populate('createdBy', 'nickName').populate('community', 'communityName')
            .sort({status: 1, dateCreated: -1}).exec(callback);
    } else {
        communitySupplement.find({community: communityId}, 'dateCreated createdBy desc community status').populate('createdBy', 'nickName').populate('community', 'communityName')
            .sort({status: 1, dateCreated: -1}).exec(callback);
    }
};

exports.updateCommunityService = function (communityId, input, callback) {
    Community.update({_id: communityId}, input, callback)
};

exports.updateSupplementStatusService = function (supplementId, callback) {

    Supplement.update({_id: supplementId}, {status: true}, callback)
};


exports.getAllCommunityNoticeService = function (communityId, callback) {

    var opt = {};
    if (communityId != '1') {
        opt.community = communityId;
    }
    Bulletins.find(opt).populate('community', '_id communityName').sort('-dateCreated').exec(function (err, result) {
        if (result != null) {
            result.forEach(function (topic) {
                topic._doc['url'] = NoticeHost + '/' + topic._id + '.html'
            });
        }
        callback(err, result);
    });
};

exports.setNoticeStatusService = function (input, callback) {
    Bulletins.update({_id: input.id}, {isValid: input.status}, callback);
}

exports.addNoticeToFreshService = function (communityId, noticeId, callback) {
    async.series([
        function (callbackInner) {
            Bulletins.findOne({_id: noticeId}, 'title community', function (err, result) {
                var temp = new freshNews();
                temp.openType = 1;
                temp.tag = freshName.notice.tagName;
                temp.bgColor = freshName.notice.bgColor;
                temp.newsId = result._id;
                temp.title = result.title;
                temp.community = result.community;
                temp.save(callbackInner);
            });
        }
        //function (callbackInner) {
        //    Bulletins.find({community: communityId}, function (err, results) {
        //        async.each(results, function (temp, callback1) {
        //            temp.isFresh = false;
        //            temp.save(callback1);
        //        }, function (err) {
        //            callbackInner(err, null);
        //        })
        //    });
        //},
        //function (callbackInner) {
        //    Bulletins.update({_id: noticeId}, {isFresh: true}, callbackInner);
        //}
    ], callback)
};

exports.getCommunityPeopleNumberService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var key = 'app:community:peopleNum';
            var field = user.community._id;

            redisClient.HGET(key, field, function (err, value) {
                if (value != null) {
                    callback(null, JSON.parse(value).num)
                } else {
                    Users.count({community: user.community._id}, function (err, count) {
                        callback(null, count);
                        redisClient.HSET(key, field, JSON.stringify({
                            id: user.community._id,
                            name: user.community.communityName,
                            num: count
                        }))
                    });
                }
            });
        }
    })
};

exports.getCommunityUserService = function (token, ts, vCode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            Users.count({community: user.community._id}, function (err, count) {
                count = 100;
                if (count <= 50) {
                    var key = 'communityId:' + user.community._id + ':around';
                    redisClient.SMEMBERS(key, function (err, value) {
                        value.push(user.community._id + '');

                        var opt = {community: {$in: value}, nickName: {$ne: null}, userType: {$ne: 'service'}};
                        if (ts != '0') {
                            opt.pinyinSort = {$gt: ts}
                        }

                        exports.getUsersService(opt, ts, user, function (err, results) {
                            delete opt.pinyinSort;

                            Users.count(opt, function (err, c) {
                                callback(null, {users: results, count: c})
                            })
                        })
                    });
                } else {
                    var opt = {community: user.community._id, nickName: {$ne: null}, userType: {$ne: 'service'}}
                    if (ts != '0') {
                        /* 宝宝树66小区三次改造 我的邻居下拉刷新重复显示数据修改 mod wangcan 20171023 start */
                        Users.findOne({
                            pinyinSort: ts,
                            community: user.community._id
                        }, 'nickName gender userType authenticationStatus pinyinSort community userRole dateCreated')
                            .exec(function (err, singleResult) {
                            var dateCreated = moment(singleResult.dateCreated).format("YYYY-MM-DD HH:mm:ss");

                            opt.dateCreated = {$lt: new Date(singleResult.dateCreated)};

                            exports.getUsersService(opt, ts, user, function (err, results) {
                                callback(null, {users: results, count: count})
                            })
                        });
                        // opt.pinyinSort = {$gt: ts}
                    } else {
                        opt.pinyinSort = {$ne: null}
                        exports.getUsersService(opt, ts, user, function (err, results) {
                            callback(null, {users: results, count: count})
                        })
                    }

                    // 分页条件
                    // ts = Number(ts) * listPageSize;
                    // skip(ts)
                    // exports.getUsersService(opt, ts, user, function (err, results) {
                    //     callback(null, {users: results, count: count})
                    // })
                    /* 宝宝树66小区三次改造 我的邻居下拉刷新重复显示数据修改 mod wangcan 20171023 end */
                }
            });
        }
    })
};

exports.getUsersService = function (opt, ts, user, callback) {
    Users.find(opt, 'nickName images  gender userType authenticationStatus pinyinSort community userRole')
        .populate('community', 'communityName')

        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170811   start   */
        // (邻居排序，新加的放在上面)
        .limit(listPageSize).sort('-dateCreated').exec(function (err, results) { // 新:按照dateCreated降序排序
        // .limit(listPageSize).sort('pinyinSort').exec(function (err, results) { // 旧:按照pinyinSort升序排序
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170811   end   */

            if (ts == '0') {
                Users.findOne({
                    mobilePhone: '66customerservice'
                }, 'nickName images  gender userType authenticationStatus pinyinSort community userRole')
                    .populate('community', 'communityName').exec(function (err, service) {

                        results.unshift(service);
                        //
                        //results.forEach(function (temp) {
                        //    if (temp.community) {
                        //        temp.community.communityName = ''
                        //    }
                        //});
                        callback(null, results)
                    });
            } else {

                //results.forEach(function (temp) {
                //    if (temp.community) {
                //        temp.community.communityName = ''
                //    }
                //});

                callback(err, results);
            }
        })
};


exports.deleteNoticeService = function (noticeId, callback) {
    Bulletins.remove({_id: noticeId}).exec(callback);
};

exports.getNoticeByIdService = function (noticeId, callback) {
    Bulletins.findOne({_id: noticeId}, callback)
};


/**
 * 获取周边小区列表
 * @param token
 * @param callback
 */
exports.aroundCommunityListService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {

            async.parallel([
                function (callbackInner) {
                    redisClient.HGET('app:community:peopleNum', user.community._id, function (err, community) {
                        if (community != null) {
                            callbackInner(null, JSON.parse(community))
                        } else {
                            Community.findOne({_id: user.community._id}, function (err, result) {
                                Users.count({community: user.community._id}, function (err, count) {
                                    var temp = {
                                        id: user.community._id,
                                        name: result.communityName,
                                        num: count
                                    };
                                    redisClient.HSET('app:community:peopleNum', user.community._id, JSON.stringify(temp));
                                    callbackInner(null, temp);
                                });
                            });
                        }
                    })
                },
                function (callbackInner) {
                    var data = [];
                    questionService.getAroundCommunityList(user, function (value) {
                        if (err)console.log(err);
                        async.each(value, function (commId, cb) {
                            Community.findOne({_id: commId}, 'communityName location', function (err, com) {

                                var dis = '';
                                var distance = geolib.getDistance(
                                    {
                                        latitude: user.community.location.latitude,
                                        longitude: user.community.location.longitude
                                    },
                                    {latitude: com.location.latitude, longitude: com.location.longitude}
                                );

                                if (distance > 1000) {
                                    var aa = distance / 1000;
                                    dis = aa.toFixed(1) + 'km';
                                } else {
                                    dis = distance + 'm';
                                }

                                var temp = {
                                    id: commId,
                                    name: com.communityName,
                                    distance: dis,
                                    order: distance
                                };


                                redisClient.HGET('app:community:peopleNum', commId + '', function (err, value) {
                                    if (value != null) {
                                        temp.num = JSON.parse(value).num;
                                        data.push(temp);
                                        cb()
                                    } else {
                                        Users.count({community: commId}, function (err, count) {
                                            temp.num = count;
                                            data.push(temp);
                                            redisClient.HSET('app:community:peopleNum', commId + '', JSON.stringify(temp))
                                            cb();
                                        });
                                    }
                                });
                            })
                        }, function (err, result) {
                            data.sort(function (a, b) {
                                return a.order - b.order;
                            });
                            callbackInner(null, data);
                        })
                    });

                    //Community.findOne({_id: user.community._id}, 'groups', function (err, result) {
                    //    if (result.groups != null && result.groups.length > 0) {
                    //        Community.find({groups: result.groups, _id: {$ne: user.community._id}})
                    //            .exec(function (err, value) {
                    //                async.each(value, function (community, callbackInner) {
                    //                    redisClient.HGET('app:community:peopleNum', community._id + '', function (err, comm) {
                    //                        if (comm != null) {
                    //                            data.push(JSON.parse(comm));
                    //                            callbackInner()
                    //                        } else {
                    //                            Users.count({community: community._id}, function (err, count) {
                    //                                var temp = {
                    //                                    id: community._id,
                    //                                    name: community.communityName,
                    //                                    num: count
                    //                                };
                    //                                data.push(temp);
                    //                                redisClient.HSET('app:community:peopleNum', community._id + '', JSON.stringify(temp))
                    //                                callbackInner();
                    //                            });
                    //                        }
                    //                    })
                    //                }, function () {
                    //                    callbackInner(null, data);
                    //                });
                    //            })
                    //    } else {
                    //        callbackInner(null, data);
                    //    }
                    //});
                    ////redisClient.zrange(key, 0, -1, function (err, value) {
                    ////    if (value != null && value.length > 0) {
                    ////
                    ////    } else {
                    ////        callbackInner(null, data);
                    ////    }
                    ////});
                }
            ], callback);
        }
    })
};

exports.getCommunityCard = function (token, callback) {
    var date = new Date();
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            card.find({
                isValid: true,
                beginTime: {$lte: date},
                endTime: {$gte: date}
            }).sort('-displayOrder').exec(function (err, result) {
                callback(err, result);
            });
        }
    })
};

exports.getCommunityCardNew = function (token, callback) {
    var date = new Date();
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            communityCard.find({
                isValid: true,
                beginDate: {$lte: date},
                endDate: {$gte: date},
                $or: [
                    {level: 0},
                    {level: 1, province: user.community.provinceId},
                    {level: 2, city: user.community.cityId},
                    {level: 3, county: user.community.countyId}
                ]
            }).sort('-dateLastModified').exec(function (err, result) {
                logger.info(user.community.province)
                async.each(result, function (temp, callbackInner) {
                    temp._doc.contentUrl = temp.url;
                    callbackInner();
                }, function (err) {
                    callback(err, result);
                })
            });
        }
    })
};

exports.getCommunityLatestNoticeService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err)
        } else {
            Bulletins.find({community: user.community._id, isValid: true}, 'title')
                .sort('-dateCreated').limit(1).exec(function (err, result) {
                    if (result != null && result.length > 0) {
                        callback(null, result[0])
                    } else {
                        callback(null, null)
                    }
                })
        }
    })
};

exports.getWeekReport = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
            if (err) {
                callback(err)
            } else {

                var beginTime = new Date(parseInt(input.bt) * 1000);
                var endTime = new Date(parseInt(input.et) * 1000);

                async.series([
                        function (callbackInner) {
                            weekReport.findOne(
                                {
                                    'community': user.community._id,
                                    'process_date': {$lte: endTime, $gte: beginTime}
                                })
                                .sort({process_date: -1})
                                .populate('contribution.uid', '_id nickName images')
                                .populate('new_neighbors.uid', '_id nickName images gender')
                                .exec(
                                function (err, result) {
                                    if (result == null) callback(err, "");
                                    var hotList = new Array();
                                    if (result.hotlist == null) callbackInner(err, result);
                                    async.eachSeries(result.hotlist, function (temp, callbackInner1) {
                                        Question.findOne({
                                            _id: temp.qid,
                                            'isValid': true
                                        }, '_id desc replies._id replies.replyDesc replies.dateReplied replies.repliedBy community replies dateCreated createdBy category')
                                            .populate('replies.repliedBy', '_id nickName images')
                                            .populate('community', 'communityName')
                                            .populate('createdBy', '_id nickName images').exec(function (err, question) {
                                                if (question != null) {
                                                    question.replies.forEach(function (reply) {
                                                            if (reply._id + '' == temp.rid) {
                                                                if (reply.repliedBy.images[0].imageURL.indexOf('http://') < 0) {
                                                                    reply._doc.headImg = imgHost + reply.repliedBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                                                                } else {
                                                                    reply._doc.headImg = reply.repliedBy.images[0].imageURL;
                                                                }
                                                                question._doc.bestReply = reply;
                                                            }
                                                        }
                                                    );

                                                    if (question.createdBy.images[0].imageURL.indexOf('http://') < 0) {
                                                        question._doc.headImg = imgHost + question.createdBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                                                    } else {
                                                        question._doc.headImg = question.createdBy.images[0].imageURL;
                                                    }
                                                    temp._doc.question = question;
                                                    callbackInner1();
                                                }
                                                else {
                                                    callbackInner1();
                                                }
                                            })
                                    }, function () {
                                        if (result.contribution != null) {
                                            async.each(result.contribution, function (temp, callbackInner) {
                                                if (temp.uid.images[0].imageURL.indexOf('http://') < 0) {
                                                    temp._doc.headImg = imgHost + temp.uid.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                                                } else {
                                                    temp._doc.headImg = temp.uid.images[0].imageURL;
                                                }
                                            });
                                        }
                                        if (result.new_neighbors != null) {
                                            async.each(result.new_neighbors, function (temp, callbackInner) {
                                                if (temp.uid.images[0].imageURL.indexOf('http://') < 0) {
                                                    temp._doc.headImg = imgHost + temp.uid.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                                                } else {
                                                    temp._doc.headImg = temp.uid.images[0].imageURL;
                                                }
                                            })
                                        }
                                        callbackInner(err, result);
                                    });
                                });
                        }
                        ,
                        function (callbackInner) {
                            weekScore.findOne({
                                userId: token,
                                dateCreated: {$lte: endTime},
                                dateCreated: {$gte: beginTime}
                            }).sort({dateCreated: -1}).exec(function (err, result) {
                                if (result == null) {
                                    var data = {
                                        userId: token
                                    }
                                    callbackInner(err, data);
                                } else {
                                    callbackInner(err, result);
                                }

                            });
                        }

                    ],
                    callback
                )
                ;
            }
        }
    )
    ;
}
;
